$.artboards = {}
$.artboards.getActive = function (document) {
	document = document && document.typename === 'Document' ? document : app.activeDocument;
	return document.artboards.length ? document.artboards[document.artboards.getActiveArtboardIndex()] : null;
};
$.artboards.createRectangle = function (art, _placement) {
	art = art && art.typename === 'artBoard' ? art : $.artboards.getActive();
	var rect = art.artboardRect,
		parent = app.activeDocument.activeLayer;
	var rectangle = parent.pathItems.rectangle(rect[1], rect[0], rect[2] - rect[0], rect[1] - rect[3]);
	if (_placement) rectangle.moveBefore(_placement);
	return rectangle;
};

$.artboards.each = function (callback, onlyCurrent) {
	var artboards = app.activeDocument.artboards
	var i = artboards.length
	if (onlyCurrent) {
		var artboard = artboards[artboards.getActiveArtboardIndex()]
		var canvasSize = getCanvasSize(artboards)
		callback([canvasSize], i)
	} else {
		var sizes = []
		while (i--) {
			var canvasSize = getCanvasSize(artboards[i])
			sizes.push(canvasSize)
			// callback(canvasSize, i)
		}
		callback(sizes, i)
	}
}
$.each = function(arr, callback) {
	for(var i = 0; i < arr.length; i++) {
		callback(arr[i], i)
	}
}

$.units = ['px', 'pt', 'pc', 'mm', 'cm', 'in']
$.artType = ['PathItem', 'GroupItem', 'CompoundPathItem', 'TextFrame', 'PlacedItem', 'SymbolItem']

Array.prototype.each = function(callback) {
	for (var index = 0; index < this.length; index++) {
		var element = this[index];
		callback(element, index, this)
	}
}

Array.prototype.stepIndex = function(elem){     
	var index = 0
	for (var i = 0; i < this.length - 1; i++) {
		var left = this[i]
		var right = this[i + 1]
		if (elem >= left && elem < right) {
			index = i
		} else if (elem >= right) {
			index = i + 1
		}
	}
	return index
}

String.prototype.inArr = function(arr) {
	/*
	 * 'a'.inArr(['a', 'b']) => true
	 */
	var has = false
	var str = this.toString()
	arr.each(function(item) {
		has = has || item === str
	})
	return has
}



/* 扩展内部元素放置方法 */
Object.prototype.toLeft = function(x, size) {
	var len = typeof x === 'number' ? x : new UnitValue(x).as('px')
	var canvas = size || getCanvasSize()
	if (!this.typename || !this.typename.inArr($.artType)) {
		return
	}
	this.left = canvas.x1 + len
}

Object.prototype.toMedian = function(size) {
	var canvas = size || getCanvasSize()
	var gap = (canvas.width - this.width) / 2
	this.left && this.left = canvas.x1 + gap
}

Object.prototype.toRight = function(x, size) {
	var len = typeof x === 'number' ? x : new UnitValue(x).as('px')
	var canvas = size || getCanvasSize()
	if (!this.typename || !this.typename.inArr($.artType)) {
		return
	}
	this.left = canvas.x2 - len - this.width
}

Object.prototype.toTop = function(x, size) {
	var len = typeof x === 'number' ? x : new UnitValue(x).as('px')
	var canvas = size || getCanvasSize()
	if (!this.typename || !this.typename.inArr($.artType)) {
		return
	}
	this.top = canvas.y1 - len
}

Object.prototype.toCenter = function(size) {
	// var len = typeof x === 'number' ? x : new UnitValue(x).as('px')
	var canvas = size || getCanvasSize()
	var gap = (canvas.height - this.height) / 2
	this.top && this.top = canvas.y1 - gap
}

Object.prototype.toBottom = function(x, size) {
	var len = typeof x === 'number' ? x : new UnitValue(x).as('px')
	var canvas = size || getCanvasSize()
	if (!this.typename || !this.typename.inArr($.artType)) {
		return
	}
	this.top = canvas.y2 + len + this.height
}

Object.prototype.setWidth = function(x, transform) {
	var len = typeof x === 'number' ? x : new UnitValue(x).as('px')
	ratio = this.width / this.height
	if (!this.typename || !this.typename.inArr($.artType)) { return	}
	this.width = len
	!transform && this.height = len / ratio
}

Object.prototype.setHeight = function(x, transform) {
	var len = typeof x === 'number' ? x : new UnitValue(x).as('px')
	ratio = this.width / this.height
	if (!this.typename || !this.typename.inArr($.artType)) { return	}
	this.height = len
	!transform && this.width = len * ratio
}

// ////////////////////////////////////////////////////////////
// $.artboards.createRectangle()

// var art = app.activeDocument.selection[0]
// art.toLeft('10mm')
// art.setWidth('20cm', true)
// art.setHeight('20cm')
// art.toRight(0)
// art.toTop('10cm')
// art.toMedian({x1:0, y1:-200, x2:300, y2:-500, width: 300, height:300})
// art.toCenter({x1:0, y1:-200, x2:300, y2:-500, width: 300, height:300})
// art.toBottom(100)

// ////////////////////////////////////////////////////////////

Object.prototype.avoidance = function(avoidance) {
	// 用于计算画板size 减去避让区域后的有效size
	if (!avoidance) {
		return this
	}
	var left =   new UnitValue (avoidance.avoidL.val || 0).as('px'),
		right =  new UnitValue (avoidance.avoidR.val || 0).as('px'),
		top = 	 new UnitValue (avoidance.avoidT.val || 0).as('px'),
		bottom = new UnitValue (avoidance.avoidB.val || 0).as('px');
	var x1 = this.x1 + left,
		y1 = this.y1 - top,
		x2 = this.x2 - right,
		y2 = this.y2 + bottom,
		W = Math.abs(x2 - x1),
		H = Math.abs(y2 - y1),
		thin = W < H ? W : H,
		wide = W >= H ? W : H;
	var size = {
		x1: x1,
		y1: y1,
		x2: x2,
		y2: y2,
		width: W,
		height: H,
		thin: thin,
		wide: wide,
		style: wide / thin,
		ratio: W / H,
	}
	return size
}

function getCanvasSize(canvas) {
	canvas = (canvas && canvas.artboardRect) || $.artboards.getActive().artboardRect

	var rect = canvas.toString().split(',')
	var x1 = +rect[0]
	var y1 = +rect[1]
	var x2 = +rect[2]
	var y2 = +rect[3]
	var W = Math.abs(x2 - x1);
	var H = Math.abs(y2 - y1);
	var thin = W < H ? W : H
	var wide = W >= H ? W : H
	var rectangle = {
		y1: y1,
		x1: x1,
		y2: y2,
		x2: x2,
		width: W,
		height: H,
		thin: thin,
		wide: wide,
		style: wide / thin,
		ratio: W / H,
	}
	return rectangle
}




Object.prototype.objectParser = function () {
    try {
        for (var i in this) {
			if (this[i] instanceof Object && !(this[i] instanceof Function)) {
				this[i] = objectParser(this[i])
			}
            if (!(this[i] instanceof Function)) {
                if (this[i] === 'true') this[i] = true;
                else if (this[i] === 'false') this[i] = false;
				else if (typeof this[i] === 'string') { this[i] = this[i].replace(/(&nbsp;)*/g, '') }
                // else if (!isNaN(parseFloat(this[i]))) this[i] = parseFloat(this[i]);
            }
        }
        return this;
    }
    catch (e) {
        alert(e);
    }
};
function objectParser (object) {
	try {
		for (var i in object) {
			if ((object[i] instanceof Function)) { continue }
			if (typeof object[i] === 'string') {
				var unit = object[i] && object[i].replace(/[0-9-.]*/g, '').replace(/(&nbsp;)*/g, '')
				if (unit && unit.toLowerCase().inArr($.units)) 
				{
					object[i] = new UnitValue(object[i].replace(/(&nbsp;)*/g, ''))

				}
				else if (!isNaN(parseFloat(object[i]))) { object[i] = parseFloat(object[i]); }
				else object[i] = object[i].replace(/(&nbsp;)*/g, '') //  空格开头 不含单位结尾 视为字符串
			}
			
			if (object[i] === 'true') object[i] = true;
			else if (object[i] === 'false') object[i] = false;
		}
        return object;
    }
    catch (e) {
        alert(e);
    }
}

Object.prototype.extend = function (userObject, deep) {
    try {
        for (var key in userObject) {
            if (this.hasOwnProperty(key)) {
                if (deep
                    && this[key] instanceof Object
                    && !(this[key] instanceof Array)
                    && userObject[key] instanceof Object
                    && !(userObject[key] instanceof Array)
                ) {
                    this[key].extend(userObject[key], deep);
                }
                else this[key] = userObject[key];
            }
        }
        return this;
    }
    catch (e) {
      alert(e);
    }
};

Array.prototype.map = function(fn,context) {
	if (typeof fn !== "function") {
		alert('Array.prototype.map need a function');
	}
	var arr = this;
	var temp = [];
	for(var i=0;i<arr.length;i++){
		var result = fn.call(context,arr[i],i,arr);
		temp.push(result);
	}
	return temp;
}
String.prototype.clearSpace = function(){
  return this.replace(/(^\s*)|(\s*$)/g, "")
}
String.prototype.toAiColor = function(){
  // 支持字符格式为: '100 70 30 0, 128 256 0' 或者 '128 0 0' (rgb 可使用 HEX)
  var colors = this.clearSpace().split(',')
  color = colors[0].hex2rgb().split(' ')
  var isRGBSpace = app.activeDocument.documentColorSpace === DocumentColorSpace.RGB
  if (colors.length === 2 && isRGBSpace) {
    color = colors[1].clearSpace().hex2rgb().split(' ')
  }
  try {
    if(color.length === 3) {
      var newColor = new RGBColor();
      newColor.red = color[0];
      newColor.green = color[1];
      newColor.blue = color[2];
    } else if(color.length === 4) {
      var newColor = new CMYKColor();
      newColor.cyan = color[0];
      newColor.magenta = color[1];
      newColor.yellow = color[2];
      newColor.black = color[3];
    }
    return newColor
  } catch (e) {
    var newColor = new RGBColor();
    newColor.red = 0;
    newColor.green = 0;
    newColor.blue = 0;
  }
  return newColor
}

String.prototype.hex2rgb = function(){
  // '#888' => '128 128 128'
  var sColor = this.toLowerCase();
  //十六进制颜色值的正则表达式
  var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
  // 如果是16进制颜色
  if (sColor && reg.test(sColor)) {
    if (sColor.length === 4) {
      var sColorNew = "#";
      for (var i=1; i<4; i+=1) {
        sColorNew += sColor.slice(i, i+1).concat(sColor.slice(i, i+1));
      }
      sColor = sColorNew;
    }
    //处理六位的颜色值
    var sColorChange = [];
    for (var i=1; i<7; i+=2) {
      sColorChange.push(parseInt("0x"+sColor.slice(i, i+2)));
    }
    return sColorChange.join(" ");
  }
  return sColor;
};